package com.itheima.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.itheima.admin.service.AdminService;
import com.itheima.xo.common.Result;
import com.itheima.xo.pojo.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author :WuJunJie
 * packageName :com.itheima.admin.controller
 * fileName :AdminController
 * creationTime :2022-11-04 16:19
 */
@RestController
@RequestMapping("admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        Admin adminInDB = adminService.findByEmail(admin.getEmail());
//        log.info("{}",adminInDB);

        String md5Password = DigestUtil.md5Hex(admin.getPassword());
        if (adminInDB==null||!adminInDB.getPassword().equals(md5Password)){
            log.info("用户名或密码错误");
            return Result.error();
        }
        // 创建JWT Token
        final String token = JWT.create()
                .setNotBefore(DateUtil.date())
                .setKey("336699".getBytes())
                .setPayload("adminId","152364561354")
                .setPayload("adminName","大傻逼")
                .setPayload("role","超级vip")
                .sign();
////            验证算法
//           JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256("123456".getBytes()));
        return Result.success(token);
    }

    @PostMapping("add")
    public Result add(@RequestBody Admin admin){
        Boolean add = adminService.add(admin);
        if(add){
            return Result.success(null);
        }
        return Result.error();
    }
}
